<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--区域数据-->
      <el-col :span="4" :xs="24">
        <div class="box-card">
          <div class="head-container">
            <el-input v-model="filterText" placeholder="请输入区域名称" clearable size="small" prefix-icon="el-icon-search"
              style="margin-bottom: 20px" />
          </div>
          <div class="head-container">
            <el-tree :data="regionList" :props="defaultProps" :expand-on-click-node="false"
              :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
              @node-click="handleNodeClick">
            </el-tree>
          </div>
        </div>
      </el-col>
      <!--房间数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
          label-width="68px">
          <el-form-item label="门禁名称" prop="userName">
            <el-input v-model="queryParams.name" placeholder="请输入门禁名称" clearable style="width: 240px"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddRegion"
              v-hasPermi="['system:user:add']">新增门禁</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="accessList" style="width: 100%">
          <el-table-column prop="name" label="门禁名称">
          </el-table-column>
          <el-table-column prop="regionName" label="区域">
          </el-table-column>
          <el-table-column prop="roomName" label="房间">
          </el-table-column>
          <el-table-column prop="deviceName" label="设备名称">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" icon="el-icon-edit" @click="setEdit(scope.row)">编辑</el-button>
              <el-button type="text" size="small" icon="el-icon-delete" @click="setDel(scope.row)">删除</el-button>
              <el-button type="text" size="small" icon="el-icon-set-up" @click="setBinding(scope.row)">绑定设备</el-button>
              <el-button type="text" size="small" icon="el-icon-user"
                @click="setBingdingUser(scope.row)">绑定用户</el-button>
              <el-button type="text" size="small" icon="el-icon-view" @click="lookBingUser(scope.row)">查看用户</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 新增门禁 -->
    <el-drawer :title="regionTitle" :visible.sync="drawer" :direction="direction" :before-close="handleClose">
      <el-form :model="formInline" class="demo-form-inline" label-position="top">
        <el-form-item label="门禁名称">
          <el-input v-model="formInline.name" placeholder="门禁名称"></el-input>
        </el-form-item>
        <el-form-item label="区域">
          <el-select v-model="formInline.regionId" placeholder="请选择区域" style="width: 100%;" @change="change">
            <el-option v-for="(item, index) in regionList" :key="index" :label="item.locationName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房间" v-if="formInline.regionId">
          <el-select v-model="formInline.roomId" placeholder="请选择房间" style="width: 100%;">
            <el-option v-for="(item, index) in userList" :key="index" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="btn">
          <el-button type="primary" @click="onSubmit">确认</el-button>
          <el-button @click="resetForm">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>


    <!-- 绑定设备 -->
    <el-dialog title="绑定设备" :visible.sync="dialogVisible" width="30%" :before-close="handleClose" @closed="closed">
      <div style="display: flex;">
        <el-select v-model="selelctDevice" placeholder="请选择">
          <el-option v-for="(item, index) in deviceList" :key="index" :label="item.deviceName" :value="item.id">
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setAddAccessRelationship">确 定</el-button>
      </span>
    </el-dialog>



    <!-- 绑定用户 -->
    <el-dialog title="成员列表" :visible.sync="dialogVisibleUser" width="50%" :before-close="handleClose">
      <el-row :gutter="20">
        <!--部门数据-->
        <el-col :span="4" :xs="24">
          <div class="head-container">
            <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search"
              style="margin-bottom: 20px" />
          </div>
          <div class="head-container">
            <el-tree :data="deptOptions" :props="defaultPropsUeser" :expand-on-click-node="false"
              :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
              @node-click="handleNodeClickUser" />
          </div>
        </el-col>
        <!--用户数据-->
        <el-col :span="20" :xs="24">
          <el-table v-loading="loading" :data="userListNew" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="用户名称" align="center" key="userName" prop="userName" :show-overflow-tooltip="true" />
            <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" :show-overflow-tooltip="true" />
            <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName"
              :show-overflow-tooltip="true" />
            <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" width="120" />
            <el-table-column label="创建时间" align="center" prop="createTime" width="160">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleUser = false">取 消</el-button>
        <el-button type="primary" @click="getAddBatchIds">确 定</el-button>
      </span>
    </el-dialog>


    <el-dialog title="门禁成员列表" :visible.sync="dialogVisiblePersonnel" width="50%" :before-close="handleClose">
      <el-row :gutter="20">
        <!--用户数据-->
        <el-table v-loading="loading" :data="userListNew" style="width: 100%;">
          <el-table-column label="用户名称" align="center" prop="userName" />
          <el-table-column label="开始时间" align="center" prop="sysUser.nickName" :show-overflow-tooltip="true" />
          <el-table-column label="结束时间" align="center" prop="deptName" :show-overflow-tooltip="true" />
          <el-table-column label="最近使用时间" align="center" prop="sysUser.loginDate">
          </el-table-column>
        </el-table>

        <pagination v-show="queryPersonnel.total > 0" :total="queryPersonnel.total" :page.sync="queryPersonnel.pageNum"
          :limit.sync="queryPersonnel.pageSize" @pagination="getList" />
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { listNoPage, listRoom } from "@/api/region/index";
import { listUser, getUser, deptTreeSelect } from "@/api/system/user";
import { accesslist, addAccess, editAccess, delAccess } from "@/api/access/index";
import { list, accessListRelationship, addAccessRelationship, updateAccessRelationship, accessListUser, addAccessUser } from '@/api/information/index';
import { re } from "mathjs";
export default {
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  data() {
    return {
      selelctDevice: "",
      filterText: '',
      dialogVisiblePersonnel: false,
      drawerRoom: false,
      dialogVisible: false,
      dialogVisibleUser: false,
      roomTitle: "新增房间",
      direction: 'rtl',
      drawer: false,
      regionTitle: "添加门禁",
      formInline: {
        id: "",
        name: "",
        regionId: "",
        roomId: "",
        regionName: "",
        roomName: ""
      },
      defaultPropsUeser: {
        children: "children",
        label: "label"
      },
      userListNew: [],
      formInlineRoom: {
        id: "",
        name: "",
        roomType: "",
        maxNumber: "",
        regionId: "",
        remarks: "",
        background: "",
        auditName: ""
      },
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      bindDeiceList: [],
      regionList: [],
      // 日期范围
      dateRange: [],
      // 门禁列表
      accessList: [],
      deviceList: [],
      // 表单参数
      form: {},
      defaultPropsDevice: {
        children: "children",
        label: "deviceName"
      },
      defaultProps: {
        children: "children",
        label: "locationName"
      },
      queryParamsRoom: {
        pageNum: 1,
        pageSize: 10,
        regionId: "",
        name: ""
      },
      queryPersonnel: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      queryParamsUser: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      ids: [],
      deptName: "",
      // 非单个禁用
      single: true,
      // 部门树选项
      deptOptions: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        regionId: "",
        roomId: "",
        regionName: "",
        roomName: ""
      },
      accessControlId: "",
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
          { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getAccessList();
    this.getDevice()
  },
  methods: {
    lookBingUser(row) {
      this.dialogVisiblePersonnel = true
      this.getaccessListUser(row);
    },
    getAddBatchIds() {
      addAccessUser({
        accessControlId: this.accessControlId,
        userId: "",
        ids: this.ids
      }).then(response => {
        this.dialogVisibleUser = false
        this.accessControlId = ""
        this.$message({
          type: 'success',
          message: '新增成功!'
        });
      });
    },

    getaccessListUser(row) {
      accessListUser({
        pageNum: 1,
        pageSize: 10,
        accessControlId: row.id,
        userId: "",
        ids: []
      }).then(response => {
        this.userListNew = response.rows;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 查询空间用户
    getListUser() {
      listUser(this.queryParamsUser).then(response => {
        this.userListNew = response.rows;
        this.queryParamsUser.total = response.total
      }
      );
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection)
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    closed() {
      this.selelctDevice = ""
    },
    handleNodeClickUser() { },
    // 获取门禁关系列表
    getAccessListRelationship(row) {
      this.accessControlId = row.id
      this.formInline = row
      accessListRelationship({
        accessControlId: row.id
      }).then(response => {
        if (response.data) {
          this.selelctDevice = response.data.deviceId
        }
      });
    },
    setAddAccessRelationship() {
      console.log(this.formInline.deviceName != null)
      if (this.formInline.deviceName != null) {
        updateAccessRelationship({
          accessControlId: this.accessControlId,
          deviceId: this.selelctDevice
        }).then(response => {
          this.getAccessList()
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          this.dialogVisible = false
        });

        return;
      }
      addAccessRelationship({
        accessControlId: this.accessControlId,
        deviceId: this.selelctDevice
      }).then(response => {
        this.getAccessList()
        this.$message({
          type: 'success',
          message: '绑定成功!'
        });
        this.dialogVisible = false
      });
    },
    handleNodeClickDeice(e) {
      console.log(e)
    },
    setDel(row) {
      this.$confirm('此操作将永久删除该门禁,' + row.name + '是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delAccess(row.id).then(response => {
          this.getAccessList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }
        );
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    setBinding(row) {
      this.dialogVisible = true
      this.getAccessListRelationship(row)
    },
    setBingdingUser(row) {
      this.dialogVisibleUser = true
      this.accessControlId = row.id
      this.userListNew = []
      this.getListUser()
        this.getDeptTree()
    },
    setEdit(row) {
      this.formInline = Object.assign({}, row)
      this.drawer = true
      this.regionTitle = "修改门禁"
    },
    // 获取设备
    getDevice() {
      list({
        pageNum: 1,
        pageSize: 999,
      }).then(res => {
        this.deviceList = res.rows
      }
      );
    },
    // 新增区域
    handleAddRegion() {
      this.drawer = true
    },
    /** 查询门禁列表 */
    getAccessList() {
      this.loading = true
      accesslist(this.queryParams).then(res => {
        this.accessList = res.rows
        this.loading = false
      }
      );
    },
    /** 查询区域列表 */
    getList() {
      listNoPage().then(response => {
        this.regionList = response.data;
        if (this.regionList.length > 0) {
          this.handleNodeClick(this.regionList[0])
        }
      }
      );
    },
    change(e) {
      this.queryParamsRoom.regionId = e
      this.getListRoom()
    },
    /** 查询房间 */
    getListRoom() {
      listRoom(this.queryParamsRoom).then(response => {
        this.userList = response.rows;
      }
      );
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
    onSubmit() {
      const regionObject = this.regionList.find(el => el.id = this.formInline.regionId);
      const roomObject = this.userList.find(el => el.id = this.formInline.roomId);
      this.formInline.roomName = roomObject.name;
      this.formInline.regionName = regionObject.locationName;
      if (this.formInline.id) {
        editAccess(this.formInline).then(res => {
          this.$message({
            message: '修改成功',
            type: 'success'
          });
          this.resetForm()
          this.getAccessList()
        }
        );
      } else {
        addAccess(this.formInline).then(res => {
          this.$message({
            message: '添加成功',
            type: 'success'
          });
          this.resetForm()
          this.getAccessList()
        }
        );
      }
    },
    resetForm() {
      this.drawer = false
      this.drawerRoom = false
      this.formInline = {
        id: '',
        locationName: ''
      }
      this.formInlineRoom = {
        id: "",
        name: "",
        roomType: "",
        maxNumber: "",
        regionId: "",
        remarks: "",
        background: "",
        auditName: ""
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.locationName.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.regionId = data.id;
      this.getAccessList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getAccessList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != undefined) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function () {
        return delUser(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    }
  }
};
</script>

<style scoped>
.demo-form-inline {
  padding: 20px;
}

.btn {
  width: 100%;
  text-align: right;
}

.box-card {
  height: 100vh;
  border-right: 1px solid #eee;
  padding: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  padding-right: 8px;
}

.el-tree-node__expand-icon.is-leaf {
  display: none;
}
</style>